package com.king.headline.util;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

;

/**
 * Created by king on 2015/12/1.
 */
public class Utils {

    public static void toggleSoftInput(Context context){
        InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 屏幕的宽度
     *
     * @return
     */
    public static int getScreenWidth() {
        return com.king.headline.util.UIUtils.getContext().getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 屏幕的高度
     *
     * @return
     */
    public static int getScreenHeight() {
        return UIUtils.getContext().getResources().getDisplayMetrics().heightPixels;
    }
    public static String getDate(int daynum) {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, daynum);//把日期往后增加n天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;

    }

    public static void dismissDialog( ProgressDialog pDialog){
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    public static boolean isPhoneNumberValid(String phone) {

        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    /**
     * 上传图片或者文件（上传时间超过10秒算超时）
     */
    public static String doPostPic(String url,  File file) throws Exception {
//            HttpPost post = new HttpPost(url);
//            HttpClient client = new DefaultHttpClient();
//            //2分钟超时
//            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
//            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
//            MultipartEntity entity = new MultipartEntity();
////            if (param != null && !param.isEmpty()) {
////                for (Map.Entry<String, String> entry : param.entrySet()) {
////                    entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
////                }
////            }
////            String str = CryptoUtil.encrypt(param.toString());
//            // 添加文件参数
//            if (file != null && file.exists()) {
//                entity.addPart("chatHead", new FileBody(file));
//            }
//
//            post.setEntity(entity);
//            HttpResponse response = client.execute(post);
//            int stateCode = response.getStatusLine().getStatusCode();
//            StringBuffer sb = new StringBuffer();
//            if (stateCode == HttpStatus.SC_OK) {
//                HttpEntity result = response.getEntity();
//                if (result != null) {
//                    InputStream is = result.getContent();
//                    BufferedReader br = new BufferedReader(
//                            new InputStreamReader(is));
//                    String tempLine;
//                    while ((tempLine = br.readLine()) != null) {
//                        sb.append(tempLine);
//                    }
//                }
//            }
//            post.abort();
//            return sb.toString();
        return null;
    }
    public static void dismissProgressDialog(ProgressDialog dialog){
        if (dialog!=null){
            dialog.dismiss();
        }
    }
    public static String getVersionName(){
        Context context = UIUtils.getContext();
        try {
                    PackageManager manager = context.getPackageManager();
                    PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
                    String version = info.versionName;
                     return version;
                 } catch (Exception e) {
                     e.printStackTrace();
                     return "";
                 }
    }

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }
    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
